package EventLoopTest.EventLoopTutorial;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.nio.charset.StandardCharsets;

/**
 * EventLoop 入门示例5：Channel与EventLoop的绑定关系
 * 学习目标：理解一个Channel始终绑定到同一个EventLoop
 */
public class Demo05_ChannelBinding {
    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(2); // 只有2个Worker
        
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                                
                                private EventLoop boundEventLoop = null;
                                
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) {
                                    // 记录第一次绑定的EventLoop
                                    boundEventLoop = ctx.channel().eventLoop();
                                    System.out.println("\n=== 客户端连接 ===");
                                    System.out.println("客户端: " + ctx.channel().remoteAddress());
                                    System.out.println("绑定EventLoop: " + boundEventLoop);
                                }
                                
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
                                    EventLoop currentEventLoop = ctx.channel().eventLoop();
                                    
                                    // 验证：每次处理消息时，EventLoop是否相同
                                    boolean isSame = (currentEventLoop == boundEventLoop);
                                    
                                    System.out.println("\n--- 收到消息 ---");
                                    System.out.println("消息内容: " + msg.toString(StandardCharsets.UTF_8));
                                    System.out.println("当前EventLoop: " + currentEventLoop);
                                    System.out.println("与初始绑定相同? " + isSame);
                                    
                                    // 响应
                                    String response = "消息已处理，由" + currentEventLoop + "处理\n";
                                    ctx.writeAndFlush(Unpooled.copiedBuffer(response, StandardCharsets.UTF_8));
                                }
                            });
                        }
                    });
            
            ChannelFuture future = bootstrap.bind(9999).sync();
            System.out.println("=== 服务器启动 ===");
            System.out.println("WorkerGroup只有2个EventLoop");
            System.out.println("多个客户端连接会轮询分配");
            System.out.println("但每个客户端始终绑定到同一个EventLoop");
            System.out.println("\n测试方法：");
            System.out.println("1. 打开多个终端，运行: telnet localhost 9999");
            System.out.println("2. 在每个终端发送多条消息");
            System.out.println("3. 观察每个连接是否始终使用同一个EventLoop");
            
            future.channel().closeFuture().sync();
            
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

